package org.tio.site.utils;

import java.util.concurrent.TimeUnit;

import org.redisson.Redisson;
import org.redisson.api.RMapCache;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.redisson.codec.FstCodec;
import org.redisson.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.site.init.PropInit;
import org.tio.utils.SystemTimer;

import com.jfinal.kit.PropKit;

/**
 * @author tanyaowu
 * 2017年8月7日 上午11:53:23
 */
public class RedisUtils {
	private static Logger log = LoggerFactory.getLogger(RedisUtils.class);

	private static RedissonClient redisson;
	static {
		try {
			PropInit.init();
			String address = "redis://" + PropKit.get("redis.ip") + ":" + PropKit.get("redis.port");
			Config config = new Config();
			config.useSingleServer().setAddress(address).setConnectionPoolSize(10);
			config.setCodec(new FstCodec());
			redisson = Redisson.create(config);
		} catch (Exception e) {
			log.error(e.toString(), e);
		}
	}

	public static RedissonClient get() {
		return redisson;
	}

	/**
	 * @param args
	 * @author tanyaowu
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws InterruptedException {

		PropInit.init();

		RedissonClient redissonClient = RedisUtils.get();

		RTopic<Object> topic = redisson.getTopic("anyTopic");
		topic.addListener(new MessageListener<Object>() {
			@Override
			public void onMessage(String channel, Object message) {
				System.out.println("channel:" + channel);
				System.out.println("message:" + message);
			}
		});

		// in other thread or JVM
		RTopic<Object> topic1 = redisson.getTopic("anyTopic");
		long clientsReceivedMessage = topic1.publish("哈哈哈");

		Thread.sleep(10000);

		String name = "test11";
		RMapCache<String, Integer> mapCache = redisson.getMapCache(name);
		String key = "key1";
		mapCache.put(key, 123, 0, TimeUnit.SECONDS, 5, TimeUnit.SECONDS);

		Integer v = mapCache.get(key);//.get(key);
		mapCache.expireAt(SystemTimer.currentTimeMillis() + 10000);//.expireAtAsync(SystemTimer.currentTimeMillis() + 10000);
		System.out.println(v);
		Thread.sleep(4000);

		//		mapCache.clear();

		v = mapCache.get(key);
		mapCache.expireAt(SystemTimer.currentTimeMillis() + 10000);
		System.out.println(v);
		Thread.sleep(4000);

		v = mapCache.get(key);
		mapCache.expireAt(SystemTimer.currentTimeMillis() + 10000);
		System.out.println(v);
		Thread.sleep(4000);

	}

	public static void shutdown() {
		redisson.shutdown();
	}

	/**
	 *
	 * @author tanyaowu
	 */
	public RedisUtils() {

	}
}
